package cn.datawin.task.process;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.datawin.spider.page.Page;
import cn.datawin.task.Rule;
import cn.datawin.task.Task;

public class PageProcessor extends AbstractProcessor {

	Page page;

	List<Object> list;

	Task task;

	@Override
	public void process(Page page) {
		this.page = page;
		Rule rule = new Rule(task.currentRule());
		super.params = new HashMap<String, String>();
		super.parseRule(rule, page);
		parseUrl(rule);
	}

	public void parseUrl(Rule rule) {
		list = new ArrayList<Object>();
			for (Map<String, String> map : rule.getExpression()) {
				String name = map.get("name");
				String pageRule = rule.getPageRule();
				String url = (String) super.params.get(name);
				if(null==url || url.equals("")) return;
				int pn=rule.getPageNum();
				if(pn==1){
					for (int i = 1; i <= rule.getPageSize(); i++) {
						String nextUrl = url.replaceAll(pageRule, pageRule.replace("\\d", i + ""));
						list.add(nextUrl);
					}
				}else if(pn>=100){
					for (int i = 0; i < rule.getPageSize(); i++) {
						String nextUrl = url.replaceAll(pageRule, pageRule.replace("\\d\\d\\d", i*pn + ""));
						list.add(nextUrl);
					}
				}else{
					for (int i = 0; i < rule.getPageSize(); i++) {
						String nextUrl = url.replaceAll(pageRule, pageRule.replace("\\d\\d", i*pn+ ""));
						list.add(nextUrl);
					}
				}
				
			}
	}

	
	@Override
	public Map<String, String> getParams() {
		return super.params;
	}

	@Override
	public List<Object> getList() {
		return list;
	}

	public Page getPage() {
		return page;
	}

	@Override
	public void setTask(Serializable task) {
		this.task = (Task) task;
	}

	@Override
	public Serializable getTask() {
		return task;
	}

}
